package com.weiiew.calculationService.craft;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

@Data
public class CraftList {
    private final Map<Integer, Double> storage;  // 使用哈希表存储非零值

    public CraftList() {
        this.storage = new HashMap<>();
    }

    // 核心方法优化
    public void set(int id, double value) {
        if (Math.abs(value) <= 0.000000001)
            storage.remove(id); // 删除id，即使它可能不存在
        else storage.put(id, value);
    }

    public double get(int id) {
        return storage.getOrDefault(id, 0.0);
    }

    // 运算方法优化
    public void specifyReduction(int id, double number) {
        set(id, get(id) - number);
    }

    public void specifyAdd(int id, double number) {
        set(id, get(id) + number);
    }

    public CraftList copy() {
        CraftList copied = new CraftList();
        copied.storage.putAll(this.storage);
        return copied;
    }

    public void scaleToOne(int id) {
        exitId(id);
        double factor = 1.0 / get(id);
        if (Double.isInfinite(factor) || Double.isNaN(factor)) {
            throw new ArithmeticException("Invalid scaling factor");
        }
        storage.replaceAll((k, v) -> v * factor);
        storage.values().removeIf(v -> v == 0.0);  // 清理缩放后的零值
    }

    public void add(CraftList other) {
        other.storage.forEach((k, v) ->
                this.storage.merge(k, v, Double::sum)
        );
        this.storage.values().removeIf(v -> v == 0.0);
    }

    public void multiple(double mul) {
        storage.replaceAll((k, v) -> v * mul);
        storage.values().removeIf(v -> v == 0.0);
    }

    // 索引验证
    private void exitId(int id) {
        if (!storage.containsKey(id)) {
            throw new IndexOutOfBoundsException(
                    String.format("id: %d is not exist", id)
            );
        }
    }
}